package mirkofrancuski.battleship.db;

import mirkofrancuski.battleship.game.Board;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class ProbabilityMatrixTable {
	private static String DEBUG_TAG = "DEBUG BoardTable";

	private static String MATRIX_TABLE = "Probability_Matrix";
	private static final String MATRIX_TABLE_ROWS = "Rows";
	private static final String ROW = "row";

	public static void onCreate(SQLiteDatabase database) {
		String createTable = "CREATE TABLE " + MATRIX_TABLE + " ("
				+ MATRIX_TABLE_ROWS + " INTEGER PRIMARY KEY, ";

		for (int i = 0; i < Board.BOARD_SIZE; i++)
			createTable += ROW + Integer.toString(i) + " INTEGER"
					+ (i != Board.BOARD_SIZE - 1 ? ", " : "");
		createTable += ")";

		database.execSQL(createTable);
	}

	public static void onUpgrade(SQLiteDatabase database, int oldVersion,
			int newVersion) {
		Log.w(HighScoreTable.class.getName(),
				"Upgrading database from version " + oldVersion + " to "
						+ newVersion + ", which will destroy all old data");
		database.execSQL("DROP TABLE IF EXISTS " + MATRIX_TABLE);
		onCreate(database);
	}

	public static void saveProbabilityMatrix(SQLiteDatabase db, int[][] matrix) {
		deleteProbabilityMatrix(db);
		ContentValues cv;
		for (int i = 0; i < Board.BOARD_SIZE; i++) {
			cv = new ContentValues();
			cv.put(MATRIX_TABLE_ROWS, i);
			for (int j = 0; j < Board.BOARD_SIZE; j++) {
				cv.put(ROW + j, matrix[i][j]);
			}
			db.insert(MATRIX_TABLE, null, cv);
		}
		Log.d(DEBUG_TAG, "Matrix saved: \n" + readMatrix(db).toString());
	}

	public static void deleteProbabilityMatrix(SQLiteDatabase db) {
		db.delete(MATRIX_TABLE, null, null);
	}

	public static int[][] restoreProbabilityMatrix(SQLiteDatabase db) {
		int[][] matrix = readMatrix(db);

		if (matrix == null)
			return null;

		Log.d(DEBUG_TAG, "Matrix read: \n" + matrix.toString());

		return matrix;
	}

	private static int[][] readMatrix(SQLiteDatabase db) {
		int[][] matrix = null;

		String selectQuery = "SELECT * FROM " + MATRIX_TABLE;
		Cursor cursor = db.rawQuery(selectQuery, null);

		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			if (matrix == null)
				matrix = new int[Board.BOARD_SIZE][Board.BOARD_SIZE];
			int i = Integer.parseInt(cursor.getString(0));
			for (int j = 0; j < Board.BOARD_SIZE; j++) {

				String number = cursor.getString(j + 1);
				// number = number.substring(ROW.length());
				matrix[i][j] = Integer.parseInt(number);
			}

		}
		return matrix;
	}
}
